package cn.sccl.dirms.dev.service.impl;

import cn.sccl.common.database.DataSet;
import cn.sccl.common.service.impl.BaseManagerImpl;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.springframework.stereotype.Service;
import org.springframework.beans.factory.annotation.Autowired;
import cn.sccl.common.dao.BaseDAO;
import cn.sccl.dirms.dev.service.DataSourceManager;
import cn.sccl.dirms.dev.dao.DataSourceDAO;
import cn.sccl.dirms.dev.model.DataSource;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 的Manager实现类
 * Created by liupan on 2017-06-25.
 */
@Service
public class DataSourceManagerImpl extends BaseManagerImpl<DataSource> implements DataSourceManager {

    @Autowired
    private DataSourceDAO dataSourceDAO;

    public DataSourceDAO getDataSourceDAO() {
        return dataSourceDAO;
    }

    @Override
    public BaseDAO<DataSource> getBaseDAO() {
        return getDataSourceDAO();
    }

    /**
     * 连接数据
     *
     * @param dataSource
     * @return
     * @throws Exception
     */
    @Override
    public JSONArray connect(DataSource dataSource, JSONObject params) throws Exception {
        if (dataSource == null) {
            JSONArray nullarry = new JSONArray();
            nullarry.add("数据项不存在。");
            return nullarry;
        }
        //没有传入参数，使用默认的参数
        JSONObject configType = JSONObject.parseObject(dataSource.getValType());
        if (params == null || params.isEmpty()) {
            params = configType;
        }else{
            if(configType!=null&&!configType.isEmpty()){
                //比对传入的参数和配置的参数key是否完全 匹配
                for(Map.Entry entry:configType.entrySet()){
                    if(!params.containsKey(entry.getKey())){
                        params.put(entry.getKey().toString(),entry.getValue());
                    }
                }
            }
        }
        if (dataSource.getDsType().equals("url")) {
            return connectRestFul(dataSource.getValStr(), dataSource.getValMethod(), params);
        }
        if (dataSource.getDsType().equals("sql")) {
            String sql = dataSource.getValStr();
            String nodeName = "";
            List paramArray = new ArrayList();

            if (params != null && !params.isEmpty()) {
                int firstbgnIndex = 0;
                int firstendIndex = 0;
                //最多100个参数
                for (int i = 0; i < 100; i++) {
                    firstbgnIndex = sql.indexOf("#{");
                    // < 都替换完了 结束循环
                    if (firstbgnIndex < 0) {
                        break;
                    }
                    //获取节点名字  通过查找 第一个${ 之后的内容来获取
                    nodeName = sql.substring(firstbgnIndex + 2,
                            sql.length());
                    firstendIndex = nodeName.indexOf("}");
                    if (firstendIndex < 0) {
                        break;
                    }
                    //获取节点名字  通过查找 第一个} 之前的内容来获取
                    nodeName = nodeName.substring(0,firstendIndex);
                    //替换为问号
                    sql = sql.replaceFirst("#\\{" + nodeName + "\\}", "?");
                    //同时写入参数数组--这样才能保证顺序一致
                    paramArray.add(params.get(nodeName));
                }
            }

            DataSet ds = getDataBase().query(sql, paramArray.toArray());
            JSONObject obj;
            JSONArray arry = new JSONArray();
            Map<String, Integer> filedMap = new HashMap<>();
            for (int i = 0; i < ds.RowCount; i++) {
                obj = new JSONObject();
                filedMap = ds.FieldsIndex;
                for (Map.Entry entry : filedMap.entrySet()) {
                    obj.put(entry.getKey().toString(), ds.getRow(i).getObject((Integer) entry.getValue()));
                }
                arry.add(obj);
            }
            return arry;
        }

        return new JSONArray();
    }

    /**
     * 获取数据
     *
     * @param key key 格式为 dsNo.键值
     * @return
     */
    @Override
    public JSONArray viewData(String key, JSONObject params) throws Exception {
        String[] array = key.split("\\.");
        if (array.length > 1) {
            String no = array[0];
            Map<String, Object> find = new HashMap<>();
            find.put("dsNo", no);
            DataSource ds = this.getBaseDAO().findUniqueBy(find);
            return this.connect(ds, params);
        } else {
            return new JSONArray();
        }
    }

    //根据 类别查询数据
    @Override
    public List<DataSource> queryDataByClassify(String classify) {
        String sql = "select d.* from t_dev_data d where 1=1 and d.delete_flag = 0" ;
        if (!"-1".equals(classify)){
            sql +=" and d.classify = ?";
            return getDataBase().query4Model(sql, DataSource.class, new Object[]{classify});
        }
        return getDataBase().query4Model(sql, DataSource.class);

    }

    /**
     * 访问rest服务
     *
     * @param Url
     * @param method
     * @param params
     * @return
     * @throws Exception
     */
    private JSONArray connectRestFul(String Url, String method, JSONObject params) throws Exception {
        byte[] bypes = new byte[]{};
        if (params != null && !"".equals(params)) {
            for (Map.Entry entry : params.entrySet()) {
                Url = Url.replace("#{" + entry.getKey() + "}", "" + params.get(entry.getKey()) + "");
            }
            if (method.toUpperCase().equals("POST")) {//get参数体现在url中
                String paramstr = Url.substring(Url.indexOf("?") + 1);
                Url = Url.replace("?" + paramstr, "");
                bypes = params.toJSONString().getBytes();
            }
        }
        //需要请求的restful地址
        URL url = new URL(Url);
        //打开restful链接
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        // 提交模式
        conn.setRequestMethod(method);//POST GET PUT DELETE
        //设置访问提交模式，表单提交
        conn.setConnectTimeout(10000);//连接超时 单位毫秒
        conn.setReadTimeout(2000);//读取超时 单位毫秒
        conn.setDoOutput(true);// 是否输入参数
        conn.setUseCaches(false);//不使用缓存
        if (method.toUpperCase().equals("POST")) {//POST写body
            OutputStream outStrm = conn.getOutputStream();
            outStrm.write(bypes);
        }
        InputStream inStream = conn.getInputStream();
        BufferedReader in = new BufferedReader(new InputStreamReader(inStream, "UTF-8"));

        StringBuffer buffer = new StringBuffer();
        String tmp = "";
        while ((tmp = in.readLine()) != null) {
            buffer.append(tmp);
        }
        String result = buffer.toString();
        if (result != null && result.charAt(0) == '{') {
            result = "[" + result + "]";
        }
        return JSONArray.parseArray(result);
    }
}